﻿create PROCEDURE Sync.SP_BoardMembers_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @BoardMembers_Temp TABLE 
		(
			BoardMemberID UniqueIdentifier,
			[BoardMemberName] nvarchar(50),
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @BoardMembers_Temp 
	   SELECT	Tbl.Col.value('BoardMemberID[1]','uniqueidentifier') BoardMemberID,
                Tbl.Col.value('BoardMemberName[1]', 'nvarchar(50)') [BoardMemberName],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/BoardMembers') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[BoardMembers] ([BoardMemberID],[BoardMemberName])
	SELECT t.[BoardMemberID],t.[BoardMemberName]
	FROM  @BoardMembers_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.BoardMembers_Tracking s
        WHERE t.BoardMemberID = s.BoardMemberID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[BoardMembers]
	SET [BoardMembers].[BoardMemberName] = t.[BoardMemberName] 
	FROM [dbo].[BoardMembers] s JOIN @BoardMembers_Temp t 
    ON t.BoardMemberID = s.BoardMemberID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.BoardMembers_Tracking r
				  WHERE t.BoardMemberID = r.BoardMemberID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[BoardMembers]
    FROM @BoardMembers_Temp t JOIN [dbo].[BoardMembers] s
    ON t.BoardMemberID = s.BoardMemberID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











